package repository

import (
	"hcy-api/structs/tables"
	"idp/global"
)

var BranchRepository = new(branchRepository)

type branchRepository struct {
}

func (r *branchRepository) GetBranchOfficePointByBranchId(branchId int64) (m tables.IdpOfficePoint, err error) {
	err = global.DB.Model(&tables.IdpOfficePoint{}).Where(&tables.IdpOfficePoint{BranchId: branchId}).Find(&m).Error
	return
}

// SaveBranchOfficePoint 保存办公室设计图标记点信息
func (r *branchRepository) SaveBranchOfficePoint(m *tables.IdpOfficePoint) (err error) {
	return global.DB.Model(&tables.IdpOfficePoint{}).Create(m).Error
}

// UpdateBranchOfficePoint 更新标记点信息
func (r *branchRepository) UpdateBranchOfficePoint(m *tables.IdpOfficePoint) (err error) {
	return global.DB.Save(m).Error
}

func (r *branchRepository) GetCityCode(uid int64) (code string, err error) {
	err = global.DB.Raw("select city_code from sys_user_extend where user_id = ? ", uid).Find(&code).Error
	return
}

func (r *branchRepository) FindMapUidByBranchId(branchId int64) (li []int64, err error) {
	err = global.DB.Raw("select uid from idp_map_branch_user where branch_id= ?", branchId).Find(&li).Error
	return
}

func (r *branchRepository) FindClientMapBranchId(clientId int64) (branchId int64, err error) {
	var m = new(tables.IdpMapBranchClient)
	err = global.DB.Model(&tables.IdpMapBranchClient{}).Where(&tables.IdpMapBranchClient{ClientId: clientId}).Find(m).Error
	branchId = m.BranchId
	return
}

func (r *branchRepository) FindClientIdsByBranchId(branchIds []int64) (clientIds []int64, err error) {
	err = global.DB.Raw("select distinct (client_id) from idp_map_branch_client where branch_id in ?", branchIds).Scan(&clientIds).Error
	return
}

// CountClientNumByBranchIds 统计分支机构下的设备数量
func (r *branchRepository) CountClientNumByBranchIds(branchIds []int64) (num int64, err error) {
	err = global.DB.Raw("select count( distinct client_id) from idp_map_branch_client where branch_id in ?", branchIds).Scan(&num).Error
	return
}
